package com.concurrent.sample.common.config;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.aop.interceptor.AsyncExecutionAspectSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@EnableAsync
@Configuration
public class ThreadPoolConfig {

  @Bean(name = AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME)
  public Executor taskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    initCommonParams(taskExecutor);
    taskExecutor.setCorePoolSize(2);
    taskExecutor.setMaxPoolSize(2);
    taskExecutor.setQueueCapacity(Integer.MAX_VALUE);
    taskExecutor.setThreadNamePrefix(AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME + "-");
    taskExecutor.initialize();
    return taskExecutor;
  }

  private void initCommonParams(ThreadPoolTaskExecutor taskExecutor) {
    taskExecutor.setKeepAliveSeconds(60);
    taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
    taskExecutor.setAwaitTerminationSeconds(60);
    taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  }

}
